﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Utility
{
    public class XmlSettings
    {
        string __path = "config.xml";
        XmlDocument xdoc = null;

        public string RootPath
        {
            get
            {
                string __dir = Path.GetDirectoryName(__path);
                if (string.IsNullOrWhiteSpace(__dir))
                {
                    __path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, __path);
                }
                return __path;
            }
            set
            {
                __path = value;
            }
        }

        public static XmlSettings Instance
        {
            get
            {
                return new XmlSettings();
            }
        }

        private XmlSettings()
        {
            xdoc = new XmlDocument();
            xdoc.Load(RootPath);
        }

        public string GetValue(string name, string attr = "")
        {
            XmlNode sel_node = xdoc.SelectSingleNode(string.Format("/settings/addValue[@name='{0}']", name));
            if (string.IsNullOrWhiteSpace(attr))
            {
                return sel_node.Attributes["value"].Value;
            }
            else
            {
                return sel_node.Attributes[attr].Value;
            }
        }

        public Dictionary<string, string> GetValues(string name, string[] attrs = null)
        {
            if (attrs == null || attrs.Length == 0)
            {
                attrs = new string[2];
                attrs[0] = "key";
                attrs[1] = "value";
            }

            XmlNodeList nodes = xdoc.SelectNodes(string.Format("/settings/addValue[@name='{0}']", name));
            List<Dictionary<string, string>> lst = new List<Dictionary<string, string>>();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (XmlNode node in nodes)
            {
                if (node.Attributes[attrs[0]] == null)
                {
                    continue;
                }

                dic[node.Attributes[attrs[0]].Value] = "";
                if (node.Attributes[attrs[1]] != null)
                {
                    dic[node.Attributes[attrs[0]].Value] = node.Attributes[attrs[1]].Value;
                }
            }
            return dic;
        }

        public XmlNodeList GetNodes(string xpath)
        {
            return xdoc.SelectNodes(xpath);
        }

        public XmlNode GetNode(string xpath)
        {
            return xdoc.SelectSingleNode(xpath);
        }
    }
}